package com.gfxy.modules.educationandservice.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gfxy.modules.common.entity.TotalScore;
import com.gfxy.modules.common.service.ITotalScoreService;
import com.gfxy.modules.common.service.impl.CurrentDateService;
import com.gfxy.modules.educationandservice.entity.EducationAndService;
import com.gfxy.modules.educationandservice.mapper.EducationAndServiceMapper;
import com.gfxy.modules.educationandservice.service.IEducationAndServiceService;

import com.gfxy.modules.excel.ExcelUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.ImportExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 育人与服务
 * @Author: jeecg-boot
 * @Date: 2021-10-06
 * @Version: V1.0
 */
@Service
public class EducationAndServiceServiceImpl extends ServiceImpl<EducationAndServiceMapper, EducationAndService> implements IEducationAndServiceService {
    private final String classificationId = "1724670188840878082";
    @Autowired
    private ITotalScoreService totalScoreService;
    @Autowired
    private CurrentDateService currentDateService;

    @Override
    public void saveAll(String date, String orgCode,String workNo, List<EducationAndService> educationAndServices) {
        QueryWrapper<EducationAndService> queryWrapper = new QueryWrapper<EducationAndService>();
        queryWrapper.eq("date", date).eq("work_no", workNo);
        this.baseMapper.delete(queryWrapper);
        this.saveBatch(educationAndServices);

        double scoreAll = educationAndServices.stream().mapToDouble(EducationAndService::getScore).sum();
        QueryWrapper<TotalScore> wrapper = new QueryWrapper<TotalScore>()
                .eq("date", date)
                .eq("teacher_id", workNo)
                .eq("classification_id", classificationId);
//        TotalScore totalScore = totalScoreService.getOne(wrapper);

        TotalScore totalScore = new TotalScore();
        totalScore.setTeacherId(workNo);

        // todo new
//        totalScore.setScoreType(5);
        BigDecimal bg = new BigDecimal(scoreAll);
        double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        totalScore.setScore(f1);
        totalScore.setOrgCode(orgCode);
        totalScore.setDate(date);
        totalScore.setClassificationId(classificationId);
        totalScore.setProjectId(1);

        boolean remove = totalScoreService.remove(wrapper);
        totalScore.setScore(scoreAll);
        totalScoreService.save(totalScore);
    }


    @Override
    public Map queryTotalScore(String date, String workNo) {
        Map map = this.baseMapper.queryTotalScore(date, workNo);
        return map;
    }

    @Override
    public List<Map> queryTotalScoreByOrgCodeAndDate(String date, String orgCode) {
        return this.baseMapper.queryTotalScoreByOrgCodeAndDate(date, orgCode);
    }


    @Override
    public Result<?> importExcel(MultipartFile file) throws IOException {
        int errorLines = 0;
        int successLines = 0;
        InputStream inputStream = file.getInputStream();
        if (!(inputStream).markSupported()) {
            inputStream = new PushbackInputStream(inputStream, 8);
        }
        Workbook book = WorkbookFactory.create(inputStream);
        Sheet sheet = book.getSheetAt(0);
        List<String> errorMessage = new ArrayList<>();



        String date = currentDateService.getCurrentDate().getCurrentDate();

        List<List<EducationAndService>> educationAndServiceTotal = new ArrayList<>();

        List<EducationAndService> educationsList = null;
        String work_no = "";
        String name = "";
        String depId = "";
        double score = 0.0;
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {

            try{
                Row row = sheet.getRow(i);
                String work_no_temp = ExcelUtil.formatCell(row.getCell(0));
                String name_temp = ExcelUtil.formatCell(row.getCell(1));
                if (!work_no_temp.isEmpty()) {

                    if(score > 25){

                        errorLines++;
                        errorMessage.add(name + "分数超过25分;");
                    }

                    educationsList = new ArrayList<>();
                    educationAndServiceTotal.add(educationsList);
                    work_no = work_no_temp;
                    name = name_temp;
                    score = 0.0;
                    depId = this.baseMapper.queryDepId(work_no);
                }

                String workContextTemp = ExcelUtil.formatCell(row.getCell(2));
                String scoreTemp = ExcelUtil.formatCell(row.getCell(3));
                if(workContextTemp.isEmpty() && scoreTemp.isEmpty()){

                } else {
                    if(workContextTemp.isEmpty()){


                        errorMessage.add(name + " 工作内容为空;");
                        continue;
                    } else if(scoreTemp.isEmpty()){


                        errorLines++;
                        errorMessage.add(name + " 成绩为空;");
                        continue;
                    } else {

                        score += Double.parseDouble(ExcelUtil.formatCell(row.getCell(3)));
                        EducationAndService education_temp = new EducationAndService();
                        education_temp.setWorkNo(work_no);
                        education_temp.setDate(date);
                        education_temp.setOrgCode(depId);
                        education_temp.setProjectName(ExcelUtil.formatCell(row.getCell(2)));
                        education_temp.setScore(Double.parseDouble(ExcelUtil.formatCell(row.getCell(3))));
                        educationsList.add(education_temp);

                    }
                }

            } catch (Exception e) {

                log.error(e.getMessage(), e);
                errorLines++;
                errorMessage.add(name + "excel 第 " + i + "行数据解析出现位置异常; ");
            }
        }



        if (errorLines == 0) {
            for (List<EducationAndService> educationAndServices : educationAndServiceTotal) {
                if(educationAndServices.size() >0){
                    successLines ++;
                    EducationAndService educationAndService = educationAndServices.get(0);
                    this.saveAll(educationAndService.getDate(), educationAndService.getOrgCode(), educationAndService.getWorkNo(), educationAndServices);
                }

            }
        }

        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);


    }

    @Override
    public List<EducationAndService> queryEducationAndServiceByDateAndTeacherId(String date, String teacherId) {
        QueryWrapper<EducationAndService> queryWrapper = new QueryWrapper<EducationAndService>();
        queryWrapper.eq("date", date).eq("work_no", teacherId);

        return this.baseMapper.selectList(queryWrapper);
    }


    public static class ExcelResult {
        private boolean isSuccess;
        private String errorMsg;

        public boolean isSuccess() {
            return isSuccess;
        }

        public void setSuccess(boolean success) {
            isSuccess = success;
        }

        public String getErrorMsg() {
            return errorMsg;
        }

        public void setErrorMsg(String errorMsg) {
            this.errorMsg = this.errorMsg + errorMsg;
        }

        public ExcelResult(boolean isSuccess, String errorMsg) {
            this.isSuccess = isSuccess;
            this.errorMsg = errorMsg;
        }
    }

}
